package com.example.controller.pc;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.annotation.Log;
import com.example.common.result.Result;
import com.example.common.result.YiFeiException;
import com.example.entity.dto.MacOffDto;
import com.example.entity.dto.MacOnDto;
import com.example.entity.dto.MoctyListByResourceIdDto;
import com.example.entity.dto.inspect.*;
import com.example.entity.dto.pc.*;
import com.example.entity.hz.IBody;
import com.example.entity.hz.IHead;
import com.example.entity.hz.MOCTA;
import com.example.entity.hz.SFCTA;
import com.example.entity.mysql.*;
import com.example.entity.vo.AddFirstInspectionXianChangNoInsertVo;
import com.example.entity.vo.SFCTAVo;
import com.example.entity.vo.pc.*;
import com.example.entity.yifei.*;
import com.example.entity.ymlConfig.YmlConfig;
import com.example.enums.*;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.mapper.pc.*;
import com.example.service.*;
import com.example.service.pc.*;
import com.example.untils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/api/schedule")
@Api(tags = "排产相关接口")
public class ScheduleController {
    @Autowired
    private IBodyService iBodyService;
    @Autowired
    private ZnxService znxService;
    @Autowired
    private MaintainplanMapper maintainplanMapper;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private ScheduleMapper scheduleMapper;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private ProductprocessresourceService productprocessresourceService;
    @Autowired
    private ResourcegroupService resourcegroupService;
    @Autowired
    private WorkresourceService workresourceService;
    @Autowired
    private WorkresourceMapper workresourceMapper;
    @Autowired
    private MoctyMapper moctyMapper;
    @Autowired
    private MoctaService moctaService;
    @Autowired
    private CoptdMapper coptdMapper;
    @Autowired
    private MoctaMapper moctaMapper;
    @Autowired
    private MacstatuslogService macstatuslogService;
    @Autowired
    private QmsmgMapper qmsmgMapper;
    @Autowired
    private SFCTEMapper sfcteMapper;
    @Autowired
    private MoclogService moclogService;
    @Autowired
    private IHeadService iHeadService;
    @Autowired
    private QmsmgService qmsmgService;
    @Autowired
    private MocworklogService mocworklogService;
    @Autowired
    private MocworklogMapper mocworklogMapper;
    @Autowired
    private ScheduleconfigService scheduleconfigService;
    @Autowired
    private SfctaMapper sfctaMapper;
    @Autowired
    private ResourcegroupMapper resourcegroupMapper;
    @Autowired
    private MochuanjilogService mochuanjilogService;
    @Autowired
    private ProductprocessresourceMapper productprocessresourceMapper;
    @Autowired
    private PersoninoutMapper personinoutMapper;
    @Autowired
    private PersoninoutService personinoutService;
    @Autowired
    private JinchuzhanlogMapper jinchuzhanlogMapper;
    @Autowired
    private JinchuzhanlogService jinchuzhanlogService;
    @Autowired
    private MaconlineinfohistoryMapper maconlineinfohistoryMapper;
    @Autowired
    private MaconlineinfohistoryService maconlineinfohistoryService;
    @Autowired
    private MaconlineinfoMapper maconlineinfoMapper;
    @Autowired
    private MaconlineinfoService maconlineinfoService;
    @Autowired
    private EqtteMapper eqtteMapper;
    @Autowired
    private EqttfMapper eqttfMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private InspectiontimeMapper inspectiontimeMapper;
    @Autowired
    private ResourceusehisMapper resourceusehisMapper;

    @ApiOperation("排产参数配置列表")
    @PostMapping("scheduleConfigList")
    public Result<List<Scheduleconfig>> scheduleConfigList() {
        List<Scheduleconfig> list = scheduleconfigService.list();
        return Result.success(list);
    }

    @ApiOperation("排产参数配置设置")
    @PostMapping("editScheduleConfig")
    public Result editScheduleConfig(@RequestBody EditScheduleConfigDto dto) {
        if(StringUtils.isEmpty(dto.getCompany())) {
            throw new CustomException("500", "参数不能为空");
        }
        Scheduleconfig scheduleconfig = new Scheduleconfig();
        BeanUtils.copyPropertiesIgnoreCase(dto, scheduleconfig);
        scheduleconfigService.update(scheduleconfig, new LambdaQueryWrapper<Scheduleconfig>().eq(Scheduleconfig::getCompany, dto.getCompany()));
        return Result.success();
    }

    @ApiOperation("排程列表")
    @PostMapping("scheduleList")
    public Result<PageInfo<PCListVo>> scheduleList(@RequestBody ScheduleDto scheduleDto) {
        PageInfo<PCListVo> pcListVoPageInfo = scheduleService.scheduleList(scheduleDto);
//        Result<ScheduleListVo> result = Result.success(list);
        return Result.success(pcListVoPageInfo);
    }

    @ApiOperation("排程列表 无分页")
    @PostMapping("scheduleListNoPage")
    public Result<List<PCListVo>> scheduleListNoPage(@RequestBody ScheduleDto scheduleDto) {
//        Result<ScheduleListVo> result = Result.success(list);
        return Result.success(scheduleService.scheduleListNoPage(scheduleDto));
    }

    @ApiOperation("按工单工序日期 查询[生产线/机器]")
    @PostMapping("selMachines")
    public Result<List<MachinesVo>> selMachines(@RequestBody SelWorkResourceDto dto) {
        List<MachinesVo> res = scheduleService.selMachinesMocta(dto);
        return Result.success(res);
    }

    @ApiOperation("按工单工序日期 查询[生产线/机器]")
    @PostMapping("selMachinesYuan")
    public Result<List<MachinesVo>> selMachinesYuan(@RequestBody SelWorkResourceDto dto) {
        List<MachinesVo> res = scheduleService.selMachines(dto);
        return Result.success(res);
    }

    @Log("添加[生产线/机器]")
    @DSTransactional
    @ApiOperation("添加[生产线/机器]")
    @PostMapping("addMachines")
    public Result addMachines(@RequestBody AddMachinesDto dto) {
        if(StringUtils.isEmpty(dto.getDate())) {
            return Result.error("排产日期不能为空");
        }
        if(TimeUtils.HZStdTime().compareTo(dto.getDate()) > 0) {
            return Result.error("不能往前排产");
        }
        // 查询是否存在 工单-工序-日期-生产线一样的，有则不能添加
        Mocty mocty1 = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getTy001, dto.getWorkSingle()).eq(Mocty::getTy002, dto.getWorkNo())
                .eq(Mocty::getTy003, dto.getDate()).eq(Mocty::getTy019, dto.getProcessNo()).eq(Mocty::getTy009, dto.getProductLine()));
        if(mocty1 != null) {
            return Result.error("已存在[生产线/机器]一样的行");
        }
        // 1. 查询工单的总数量
        MOCTA mocta = moctaService.getOne(new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA001, dto.getWorkSingle()).eq(MOCTA::getTA002, dto.getWorkNo()));
        if(mocta.getTA011().trim().equals("Y") || mocta.getTA011().trim().equals("y")) {
            return Result.error("添加失败, 该工单已结束!!");
        }
        Double allSum = mocta.getTA015().doubleValue();
        // 2. 查询已经排产的数量
        Double alreadySum = moctyMapper.getTy004SumByTY001TY002(dto.getWorkSingle(), dto.getWorkNo(), dto.getProcessNo());
        if(allSum.compareTo(alreadySum) == 0) {
            return Result.error("添加失败, 排产数量已满!!");
        }
        // 3. 对比数量超了多少，超的话，按最多能排产的数量排
        Boolean flag = false;
        if(alreadySum + dto.getNums() > allSum) {
            dto.setNums(allSum - alreadySum);
            flag = true;
        }
        Mocty mocty = new Mocty();
        mocty.setCompany("");
        mocty.setCreateDate(TimeUtils.getNowTime());
        mocty.setCreator(SecurityUtils.getLoginUser().getUsername());
        mocty.setFlag(1D);
        mocty.setTy001(dto.getWorkSingle());
        mocty.setTy002(dto.getWorkNo());
        mocty.setTy003(dto.getDate());
        mocty.setTy004(dto.getNums());
        mocty.setTy009(dto.getProductLine());
        mocty.setTy019(dto.getProcessNo());
        mocty.setUdf11(UUID.randomUUID().toString());
        mocty.setUdf12(UUID.randomUUID().toString());
        Moclog moclog = new Moclog();
        moclog.setTa001(mocty.getTy001());
        moclog.setTa002(mocty.getTy002());

        moclog.setCreator(SecurityUtils.getLoginUser().getUsername());
        moclog.setCreatetime(TimeUtils.getFullNowTime());

        if(StringUtils.isNotEmpty(dto.getProductLine()) && !"****".equals(dto.getProductLine())) {
            mocty.setUdf01(MOCStatusEnum.DaiJinZhan.getValue());
            moclog.setStatus(MOCStatusEnum.DaiJinZhan.getValue());
        }else{
            mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
            moclog.setStatus(MOCStatusEnum.DaiPaiJi.getValue());
        }

        mocty.setUdf03(dto.getRemark());
        mocty.setUdf05(UUID.randomUUID().toString());
        moclog.setMoctyudf05(mocty.getUdf05());
        moctyMapper.insert(mocty);
        // 如果在品号工序资源表中有绑定默认的资源，直接写入表中。
        List<Productprocessresource> list = productprocessresourceService.selPPRList(new PPRDto(dto.getProductId(),
                dto.getProcessId(), dto.getProcessNo(), "****".equals(dto.getProductLine()) ? null : Integer.parseInt(dto.getProductLine())));
        Resourcegroup one = null;
        if(StringUtils.isNotEmpty(dto.getProductLine()) && !"****".equals(dto.getProductLine())) {
            one = resourcegroupService.getOne(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupId, dto.getProductLine()));
            if(one == null) {
                throw new CustomException("500", "设备或生产线不存在");
            }
            moclog.setMacid(one.getResourceGroupId());
            moclog.setMacno(one.getResourceGroupNO());
            moclog.setMacname(one.getResourceGroupName());
        }
        moclogService.save(moclog);
        for(Productprocessresource t : list) {
            Workresource workresource = new Workresource();
            BeanUtils.copyPropertiesIgnoreCase(t, workresource);
            workresource.setWorkSingle(dto.getWorkSingle());
            workresource.setWorkNo(dto.getWorkNo());
            workresource.setDate(dto.getDate());
            workresource.setCreateTime(TimeUtils.getFullNowTime());
            workresource.setWorkResourceId(UUID.randomUUID().toString());
            workresource.setProductLineId(mocty.getUdf05());   // 和生产线进行绑定
            if(dto.getProductLine() != null && !"****".equals(dto.getProductLine().trim()) && t.getResourceGroupId().equals(one.getResourceGroupParentId())) {   // 如果有具体资源 && 具体资源和
                workresource.setResourceId(Integer.parseInt(dto.getProductLine()));
            }
            workresourceService.save(workresource);
        }

//        moctaMapper.modifyMOCTA(dto.getWorkSingle(), dto.getWorkNo());
        if(flag) return Result.success("添加成功, 最多只能排产" + dto.getNums() + "!!");
        return Result.success("添加成功");
    }

    @Log("添加具体资源组")
    @DSTransactional
    @ApiOperation("添加具体资源组")
    @PostMapping("addResourceGroup")
    public Result addResourceGroup(@RequestBody AddResourceGroupDto dto) {
        MOCTA mocta = moctaService.getOne(new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA001, dto.getWorkSingle()).eq(MOCTA::getTA002, dto.getWorkNo()));
        if(mocta.getTA011().trim().equals("Y") || mocta.getTA011().trim().equals("y")) {
            return Result.error("添加失败, 该工单已结束!!");
        }
        Mocty needToUpdateMocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getProductLineId()));
        if(needToUpdateMocty == null) {
            return Result.error("排产UUID不存在!!");
        }
        int count = macstatuslogService.count(new LambdaQueryWrapper<Macstatuslog>().eq(Macstatuslog::getMoctyudf05, dto.getProductLineId()));
        if(count > 0) {
            return Result.error("该排产单已有后续机器操作单据,不可修改");
        }
        // 查询是否存在 工单-工序-工艺-日期-生产线-资源组ID 一样的，有则不能添加
        Workresource one = workresourceService.getOne(new LambdaQueryWrapper<Workresource>()
                .eq(Workresource::getProductLineId, dto.getProductLineId()).eq(Workresource::getResourceGroupId, dto.getResourceGroupId()));
        if(one != null) {
            return Result.error("已存在[具体资源]一样的行");
        }
        Workresource workresource = new Workresource();
        workresource.setWorkResourceId(UUID.randomUUID().toString());
        BeanUtils.copyPropertiesIgnoreCase(dto, workresource);
        workresource.setCreateTime(TimeUtils.getFullNowTime());
        workresourceService.save(workresource);
        Integer originIdById = resourcegroupService.getOriginIdById(dto.getResourceGroupId());
        if(originIdById.equals(1) || originIdById.equals(2)) {
            // 如果添加的是，生产线/机器，。则需要修改MOCTY中的生产线
            // 1.首先判断有没有一样的行
            Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getTy001, dto.getWorkSingle()).eq(Mocty::getTy002, dto.getWorkNo())
                    .eq(Mocty::getTy003, dto.getDate()).eq(Mocty::getTy019, dto.getProcessNo()).eq(Mocty::getTy009, dto.getResourceId().toString()));
            if(mocty != null && !mocty.getUdf05().equals(dto.getProductLineId())) {
                throw new YiFeiException(500, "已存在[生产线/机器]一样的行");
            }
            // 2.修改mocty中的值
            Mocty t = new Mocty();
            t.setCompany("");
            t.setModiDate(TimeUtils.getNowTime());
            t.setModifier(SecurityUtils.getLoginUser().getUsername());
            t.setTy009(dto.getResourceId().toString());
            moctyMapper.update(t, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getProductLineId()));
        }
        return Result.success("添加成功");
    }

    @Log("删除[生产线/机器]")
    @DSTransactional
    @ApiOperation("删除[生产线/机器]")
    @PostMapping("delMachines")
    public Result delMachines(@RequestBody DelDto dto) {

        Mocty needToUpdateMocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUUID()));
        if(needToUpdateMocty == null) {
            return Result.error("排产UUID不存在!!");
        }
        int count = macstatuslogService.count(new LambdaQueryWrapper<Macstatuslog>().eq(Macstatuslog::getMoctyudf05, dto.getUUID()));
        if(count > 0) {
            return Result.error("该排产单已有后续机器操作单据,不可修改");
        }

        List<IHead> iHeadList = iHeadService.list(new LambdaQueryWrapper<IHead>().eq(IHead::getMoctyudf05, dto.getUUID()));
        if(iHeadList.size() > 0) {
            StringBuffer sb = new StringBuffer();
            for(IHead t : iHeadList) sb.append(t.getType() + "-" + t.getUid() + "  ");
            throw new CustomException("500", "删除失败, 已有检验单据: " + sb.toString());
        }

//        System.out.println(dto);
        Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUUID()));
        if("Y".equals(mocty.getTy018().trim())) {
            throw new CustomException("500", "删除失败, 已有领料单");
        }
        moctyMapper.delete(new LambdaQueryWrapper<Mocty>()
                .eq(Mocty::getUdf05, dto.getUUID()));
        workresourceService.remove(new LambdaQueryWrapper<Workresource>()
                .eq(Workresource::getProductLineId, mocty.getUdf05()));
//        moctaMapper.modifyMOCTA(mocty.getTy001(), mocty.getTy002());
        return Result.success("删除成功");
    }

    @Log("删除具体资源组")
    @ApiOperation("删除具体资源组")
    @DSTransactional
    @PostMapping("delResourceGroup")
    public Result delResourceGroup(@RequestBody DelDto dto) {
        Workresource one = workresourceService.getOne(new LambdaQueryWrapper<Workresource>()
                .eq(Workresource::getWorkResourceId, dto.getUUID()));
        List<IHead> iHeadList = iHeadService.list(new LambdaQueryWrapper<IHead>().eq(IHead::getMoctyudf05, one.getProductLineId()));
        if(iHeadList.size() > 0) {
            StringBuffer sb = new StringBuffer();
            for(IHead t : iHeadList) sb.append(t.getType() + "-" + t.getUid() + "  ");
            throw new CustomException("500", "删除失败, 已有检验单据: " + sb.toString());
        }
        Mocty needToUpdateMocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, one.getProductLineId()));
        if(needToUpdateMocty == null) {
            return Result.error("排产UUID不存在!!");
        }
        int count = macstatuslogService.count(new LambdaQueryWrapper<Macstatuslog>().eq(Macstatuslog::getMoctyudf05, one.getProductLineId()));
        if(count > 0) {
            return Result.error("该排产单已有后续机器操作单据,不可修改");
        }
//        System.out.println(dto);
        workresourceService.remove(new LambdaQueryWrapper<Workresource>()
                .eq(Workresource::getWorkResourceId, dto.getUUID()));
        return Result.success("删除成功");
    }

    @Log("编辑[生产线/机器]")
    @DSTransactional
    @ApiOperation("编辑[生产线/机器]")
    @PostMapping("editMachines")
    public Result editMachines(@RequestBody EditMachinesDto dto) {
        if(StringUtils.isEmpty(dto.getUUID())) {
            return Result.error("编辑ID为空");
        }
        Mocty needToUpdate = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUUID()));
        if(needToUpdate == null) {
            return Result.error("排产UUID不存在");
        }
        int count = macstatuslogService.count(new LambdaQueryWrapper<Macstatuslog>().eq(Macstatuslog::getMoctyudf05, dto.getUUID()));
        if(count > 0) {
            return Result.error("该排产单已有后续机器操作单据,不可修改");
        }
        if(dto.getNums() == null) {
            throw new CustomException("500", "编辑失败, 数量不能为空!");
        }
        List<IHead> iHeadList = iHeadService.list(new LambdaQueryWrapper<IHead>().eq(IHead::getMoctyudf05, dto.getUUID()));
        if(iHeadList.size() > 0) {
            StringBuffer sb = new StringBuffer();
            for(IHead t : iHeadList) sb.append(t.getType() + "-" + t.getUid() + "  ");
            throw new CustomException("500", "操作失败, 已有检验单据: " + sb.toString());
        }
        // 查询是否存在 工单-工序-日期-生产线一样的，有则不能添加
        Mocty mocty1 = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getTy001, needToUpdate.getTy001()).eq(Mocty::getTy002, needToUpdate.getTy002())
                .eq(Mocty::getTy003, needToUpdate.getTy003()).eq(Mocty::getTy019, needToUpdate.getTy019()).eq(Mocty::getTy009, dto.getProductLine()));
        if(mocty1 != null && !mocty1.getUdf05().equals(dto.getUUID())) {
            return Result.error("已存在[生产线/机器]一样的行");
        }
        // 1. 查询工单的总数量
        MOCTA mocta = moctaService.getOne(new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA001, needToUpdate.getTy001()).eq(MOCTA::getTA002, needToUpdate.getTy002()));
        Double allSum = mocta.getTA015().doubleValue();
        // 2. 查询已经排产的数量
        Double alreadySum = moctyMapper.getTy004SumByTY001TY002(needToUpdate.getTy001(),  needToUpdate.getTy002(), needToUpdate.getTy019());
        // 3. 减去这个修改之前的排产数量
        alreadySum -= needToUpdate.getTy004();
        // 4. 对比数量超了多少，超的话，按最多能排产的数量排
        Boolean flag = false;
        if(alreadySum + dto.getNums() > allSum) {
            dto.setNums(allSum - alreadySum);
            flag = true;
        }
        Mocty mocty = new Mocty();
        mocty.setCompany("");
        mocty.setModiDate(TimeUtils.getNowTime());
        mocty.setModifier(SecurityUtils.getLoginUser().getUsername());
        mocty.setTy004(dto.getNums()); mocty.setTy009(dto.getProductLine()); mocty.setUdf03(dto.getRemark());

        Moclog moclog = new Moclog();
        moclog.setTa001(needToUpdate.getTy001());
        moclog.setTa002(needToUpdate.getTy002());
        moclog.setMoctyudf05(needToUpdate.getUdf05());
        moclog.setCreator(SecurityUtils.getLoginUser().getUsername());
        moclog.setCreatetime(TimeUtils.getFullNowTime());

        if(StringUtils.isNotEmpty(dto.getProductLine()) && !"****".equals(dto.getProductLine())) {
            mocty.setUdf01(MOCStatusEnum.DaiJinZhan.getValue());
            moclog.setStatus(MOCStatusEnum.DaiJinZhan.getValue());
            moclog.setMacid(Integer.parseInt(dto.getProductLine()));
        }else{
            mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
            moclog.setStatus(MOCStatusEnum.DaiPaiJi.getValue());
        }
        moclogService.save(moclog);
        moctyMapper.update(mocty, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUUID()));
        //
        List<Workresource> list = workresourceService.list(new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, dto.getUUID()));
        int cnt = 0;  Workresource needWorkresource = null;
        List<Resourcegroup> list333 = resourcegroupService.list();
        Map<Integer, Resourcegroup> posMap = new HashMap<>();
        for(Resourcegroup t : list333) {
            posMap.put(t.getResourceGroupId(), t);
        }
        for(Workresource workresource : list) {
            if(workresource.getResourceGroupId() != null) {
                Integer originIdById = resourcegroupService.getOriginIdById(workresource.getResourceGroupId(), posMap);
                if(originIdById.equals(1) || originIdById.equals(2)) {
                    cnt++;  needWorkresource = workresource;
                }
            }
        }
        if(cnt > 1) {
            throw new YiFeiException(500, "生产线/设备不能有多行");
        }
        if(cnt == 0 && !"****".equals(dto.getProductLine())) {
            Workresource workresource = new Workresource();
            workresource.setWorkResourceId(UUID.randomUUID().toString());
            workresource.setWorkSingle(needToUpdate.getTy001());
            workresource.setWorkNo(needToUpdate.getTy002());
            workresource.setProcessNo(dto.getProcessNo());
            workresource.setProcessId(dto.getProcessId());
            workresource.setResourceGroupId(resourcegroupService.getOne(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupId, Integer.parseInt(dto.getProductLine()))).getResourceGroupParentId());
            workresource.setResourceId(Integer.parseInt(dto.getProductLine()));
            workresource.setDate(needToUpdate.getTy003());
            Productprocessresource one = productprocessresourceService.getOne(new LambdaQueryWrapper<Productprocessresource>()
                    .eq(Productprocessresource::getProductId, mocta.getTA006().trim()).eq(Productprocessresource::getProcessNo, dto.getProcessNo())
                    .eq(Productprocessresource::getProcessId, dto.getProcessId()).eq(Productprocessresource::getResourceGroupId, workresource.getResourceGroupId()));
            if(one != null) {
                workresource.setBeat(one.getBeat());
                workresource.setQuota(one.getQuota());
            }else{
                workresource.setBeat(0D);
                workresource.setQuota(0D);
            }
            workresource.setCreateTime(TimeUtils.getFullNowTime());
            workresource.setProductLineId(dto.getUUID());
            workresourceService.save(workresource);
        }else if(cnt == 1 && !"****".equals(dto.getProductLine())){
            needWorkresource.setResourceId(Integer.parseInt(dto.getProductLine()));
            needWorkresource.setResourceGroupId(resourcegroupService.getOne(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupId, Integer.parseInt(dto.getProductLine()))).getResourceGroupParentId());
            workresourceService.update(needWorkresource, new LambdaQueryWrapper<Workresource>().eq(Workresource::getWorkResourceId, needWorkresource.getWorkResourceId()));
        }
//        moctaMapper.modifyMOCTA(needToUpdate.getTy001(), needToUpdate.getTy002());
        if(flag) return Result.success("编辑成功, 最多只能排" + dto.getNums() + "!!");
        return Result.success("编辑成功");
    }

    @Log("编辑具体资源组")
    @DSTransactional
    @ApiOperation("编辑具体资源组")
    @PostMapping("editResourceGroup")
    public Result editResourceGroup(@RequestBody EditResourceGroupDto dto) {
        if(StringUtils.isEmpty(dto.getUUID())) {
            return Result.error("编辑ID为空");
        }
        Workresource needToUpdate = workresourceService.getOne(new LambdaQueryWrapper<Workresource>().eq(Workresource::getWorkResourceId, dto.getUUID()));
        if(needToUpdate == null) {
            return Result.error("需要编辑的ID不存在");
        }
        Mocty mocty111 = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, needToUpdate.getProductLineId()));
//        if("Y".equals(mocty111.getTy018().trim())) {
//            throw new CustomException("500", "编辑失败, 已有领料单");
//        }
        List<IHead> iHeadList = iHeadService.list(new LambdaQueryWrapper<IHead>().eq(IHead::getMoctyudf05, needToUpdate.getProductLineId()));
        if(iHeadList.size() > 0) {
            StringBuffer sb = new StringBuffer();
            for(IHead t : iHeadList) sb.append(t.getType() + "-" + t.getUid() + "  ");
            throw new CustomException("500", "删除失败, 已有检验单据: " + sb.toString());
        }
        Workresource one = workresourceService.getOne(new LambdaQueryWrapper<Workresource>()
                .eq(Workresource::getProductLineId, needToUpdate.getProductLineId()).eq(Workresource::getResourceGroupId, dto.getResourceGroupId()));
        if(one != null && !one.getWorkResourceId().equals(dto.getUUID())) {
            return Result.error("已存在[资源组]一样的行");
        }
        Workresource workresource = new Workresource();
        BeanUtils.copyPropertiesIgnoreCase(dto, workresource);
        workresourceService.update(workresource, new LambdaQueryWrapper<Workresource>()
                .eq(Workresource::getWorkResourceId, dto.getUUID()));

        Integer originIdById = resourcegroupService.getOriginIdById(dto.getResourceGroupId());
        if(originIdById.equals(1) || originIdById.equals(2)) {
            // 如果添加的是，生产线/机器，。则需要修改MOCTY中的生产线
            // 1.首先判断有没有一样的行
            Mocty needToUpdateMocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, needToUpdate.getProductLineId()));
            Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getTy001, needToUpdateMocty.getTy001()).eq(Mocty::getTy002, needToUpdateMocty.getTy002())
                    .eq(Mocty::getTy003, needToUpdateMocty.getTy003()).eq(Mocty::getTy019, needToUpdateMocty.getTy019()).eq(Mocty::getTy009, dto.getResourceId().toString()));
            if(mocty != null && !mocty.getUdf05().trim().equals(needToUpdateMocty.getUdf05().trim())) {
                throw new YiFeiException(500, "已存在[生产线/机器]一样的行");
            }
            // 2.修改mocty中的值
            Mocty t = new Mocty();
            t.setCompany("");
            t.setModiDate(TimeUtils.getNowTime());
            t.setModifier(SecurityUtils.getLoginUser().getUsername());
            t.setTy009(dto.getResourceId().toString());
            if(StringUtils.isNotEmpty(t.getTy009()) && !"****".equals(t.getTy009())) {
                t.setUdf01(MOCStatusEnum.DaiJinZhan.getValue());
            }else{
                t.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
            }
            moctyMapper.update(t, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, needToUpdate.getProductLineId()));
        }

        return Result.success("编辑成功");
    }

    @ApiOperation("查看物料状况(机台上料确认版)")
    @PostMapping("getMaterialStatusShangLiaoConfrim")
    public Result<List<MaterialStatusVo>> getMaterialStatusShangLiaoConfrim(@RequestBody MaterialStatusDto materialStatusDto) {
        // 只需要读出已领料的行
        Scheduleconfig scheduleconfig = scheduleconfigService.getOne(new LambdaQueryWrapper<Scheduleconfig>().eq(Scheduleconfig::getCompany, YmlConfig.getYFCOMPANY()));
        if(scheduleconfig == null) {
            throw new CustomException("500", "先创建" + YmlConfig.getYFCOMPANY() + "的排产配置数据");
        }
        if(scheduleconfig.getSchedulemode() == null || scheduleconfig.getSchedulemode().equals(1)) {

        } else {  //
            materialStatusDto.setGY(null);
        }
        return Result.success(scheduleMapper.materialStatusShangLiaoConfrim(materialStatusDto));
    }

    @ApiOperation("查看物料状况")
    @PostMapping("getMaterialStatus")
    public Result<List<MaterialStatusVo>> materialStatus(@RequestBody MaterialStatusDto materialStatusDto) {
        Scheduleconfig scheduleconfig = scheduleconfigService.getOne(new LambdaQueryWrapper<Scheduleconfig>().eq(Scheduleconfig::getCompany, YmlConfig.getYFCOMPANY()));
        if(scheduleconfig == null) {
            throw new CustomException("500", "先创建" + YmlConfig.getYFCOMPANY() + "的排产配置数据");
        }
        if(scheduleconfig.getSchedulemode() == null || scheduleconfig.getSchedulemode().equals(1)) {

        } else {  //
            materialStatusDto.setGY(null);
        }
        return Result.success(scheduleService.materialStatus(materialStatusDto));
    }

    @ApiOperation("查看物料状况(查看到每天的派工单)")
    @PostMapping("materialStatusTongShuai")
    public Result<List<MaterialStatusVo>> materialStatusTongShuai(@RequestBody MaterialStatusDto materialStatusDto) {
        Scheduleconfig scheduleconfig = scheduleconfigService.getOne(new LambdaQueryWrapper<Scheduleconfig>().eq(Scheduleconfig::getCompany, YmlConfig.getYFCOMPANY()));
        if(scheduleconfig == null) {
            throw new CustomException("500", "先创建" + YmlConfig.getYFCOMPANY() + "的排产配置数据");
        }
        if(scheduleconfig.getSchedulemode() == null || scheduleconfig.getSchedulemode().equals(1)) {

        } else {  //
            materialStatusDto.setGY(null);
        }
        return Result.success(scheduleService.materialStatusTongShuai(materialStatusDto));
    }

    @ApiOperation("查看排产状况")
    @PostMapping("getScheduleStatus")
    public Result<List<ScheduleStatusVo>> getScheduleStatus(@RequestBody ScheduleStatusDto dto) {
        List<String> dates = moctyMapper.getDates(dto.getDB(), dto.getDH(), dto.getGX());
        List<ScheduleStatusVo> res = new ArrayList<>();
        for(String date : dates) {
            ScheduleStatusVo scheduleStatusVo = new ScheduleStatusVo();
            SelWorkResourceDto t = new SelWorkResourceDto();
            t.setWorkSingle(dto.getDB());  t.setWorkNo(dto.getDH());  t.setDate(date);  t.setProcessNo(dto.getGX());  t.setProcessId(dto.getGY());
            List<MachinesVo> list = scheduleService.selMachinesChaKanPaiChanStatus(t);
            double sum = 0;
            for(MachinesVo log : list) {
                sum += log.getNums();
            }
            scheduleStatusVo.setGY(dto.getGY());
            scheduleStatusVo.setGX(dto.getGX());
            scheduleStatusVo.setDate(date);
            scheduleStatusVo.setNums(sum);
            scheduleStatusVo.setScheduleStatus(list);
            scheduleStatusVo.setDB(dto.getDB());
            scheduleStatusVo.setDH(dto.getDH());
            scheduleStatusVo.setProductId(dto.getProductId());
            res.add(scheduleStatusVo);
        }
        return Result.success(res);
    }

    @ApiOperation("按照销售订单展示排产")
    @PostMapping("scheduleListByCoptc")
    public Result<PageInfo<PCorderList>> scheduleListByCoptc(@RequestBody PCcoptcDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<Coptd> list = coptdMapper.coptdList(dto);
        PageInfo<Coptd> pageInfo = new PageInfo(list);
        List<PCorderList> res = new ArrayList<>();
        // 审核码是Y  结束码是N
//        List<Coptd> list = coptdService.list(new LambdaQueryWrapper<Coptd>().eq(Coptd::getTd016, "N").eq(Coptd::getTd021, "Y"));
        for(Coptd coptd : pageInfo.getList()) {
            PCorderList zhi = new PCorderList();
            zhi.setMoctaDiGui(scheduleService.COPTDStage(coptd.getTd001().trim(), coptd.getTd002().trim(), coptd.getTd003().trim(), dto.getStartTime(), dto.getEndTime(), coptd.getTd004().trim()));
            zhi.setOrderType(coptd.getTd001());  zhi.setOrderNo(coptd.getTd002());  zhi.setOrderSerialNo(coptd.getTd003());
            res.add(zhi);
        }
        PageInfo<PCorderList> ans = new PageInfo(list);
        BeanUtils.copyPropertiesIgnoreCase(pageInfo, ans);
        ans.setList(res);
        return Result.success(ans);
    }

    /**
     *     @ApiModelProperty("工单单别")
     *     private String workSingle;
     *     @ApiModelProperty("工单号")
     *     private String workNo;
     * @return
     */
    @ApiOperation("配料单")
    @PostMapping("peiLiaoDan/{workSingle}/{workNo}")
    public Result<PeiLiaoDan> peiLiaoDan(@PathVariable String workSingle, @PathVariable String workNo) {
        PeiLiaoDan res = scheduleMapper.peiLiaoDan(workSingle, workNo);
        res.setList(scheduleMapper.peiLiaoDanList(workSingle, workNo));
        if(res.getList() != null) {
            for(PeiLiaoDanItem t : res.getList()) {
                if(StringUtils.isEmpty(t.getLlMethod())) continue;
                switch (t.getLlMethod()) {
                    case "1" :
                        t.setLlMethod("1:逐批领料");
                        break;
                    case "2" :
                        t.setLlMethod("2:自动扣料");
                        break;
                    case "3" :
                        t.setLlMethod("3:单独领料");
                        break;
                    case "5" :
                        t.setLlMethod("5.依包装发料");
                        break;
                }
            }
        }
        return Result.success(res);
    }

    @ApiOperation("获取正在上机的Mocty列表")
    @PostMapping("moctyListOn")
    public Result<List<MoctyPlus>> moctyListOn() {
        List<MoctyPlus> moctyList = moctyMapper.moctyListOn(MOCStatusEnum.ShengChanZhong.getValue());
        return Result.success(moctyList);
    }

//    @MessageNotify("通过机器号获取正在上机的Mocty")
    @ApiOperation("通过机器号获取正在上机的Mocty")
    @PostMapping("moctyOn")
    public Result<MoctyPlus> moctyOn(@RequestBody MoctyOnDto dto) {
        Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMachineNo()));
        if(resource == null) {
            throw new CustomException("500", "机器不存在");
        }
        if(!MachineStatusEnum.JiaGong.getValue().equals(resource.getStatus().trim())
                && !MachineStatusEnum.GuZhan.getValue().equals(resource.getStatus().trim())
                && !MachineStatusEnum.ZanTing.getValue().equals(resource.getStatus().trim())) {
            throw new CustomException("200", "该机器没有进站的任务,请选择进站任务");
        }
        MoctyPlus moctyPlus = moctyMapper.getMoctyPlus(resource.getMoctyudf05().trim());
        if(moctyPlus == null) {
            throw new CustomException("500", "该排产单数据不正确");
        }
        IHead iHead = iHeadService.getOne(new LambdaQueryWrapper<IHead>().eq(IHead::getMoctyudf05, resource.getMoctyudf05().trim())
                .eq(IHead::getJinzhanUuid, resource.getJinzhanUuid()).eq(IHead::getType, "SJ"));
        if(iHead != null) moctyPlus.setSjNo(iHead.getUid().toString());
        moctyPlus.setBgNums(sfcteMapper.getAlreadyBGmocty(moctyPlus.getUdf05().trim(), moctyPlus.getTy019()));

//        moctyPlus.setTy001(moctyPlus.getTy001().trim());
//        moctyPlus.setTy002(moctyPlus.getTy002().trim());
//        moctyPlus.setTy003(moctyPlus.getTy003().trim());
//        List<MoctyPlus> tList = new ArrayList<>();  tList.add(moctyPlus);
//        List<SelMoctyScheduleTypeVo> list = moctyMapper.selMoctyScheduleType(TimeUtils.HZStdTime(), tList);
//        if(list != null && list.size() > 0) {
//            Double x = new Double(0);
//            for(SelMoctyScheduleTypeVo t : list) {
//                x += t.getTY004();
//            }
//            moctyPlus.setNowDateNums(x);
//        }

        if("ST4".equals(moctyPlus.getWorkCenterId().trim()) || "ST6".equals(moctyPlus.getWorkCenterId().trim())) {
            List<SFCTAVo> sfctaVos = sfcteMapper.querySfctaVo(moctyPlus.getTy001(), moctyPlus.getTy002());
            moctyPlus.setSfctaVoList(sfctaVos);
        }else{
            List<MoctyPlus> moctyPlusList = new ArrayList<>();
            List<Mocty> moctyList = getTongZuMocty(moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, resource.getMoctyudf05())));
            for(Mocty mocty : moctyList) {
                MoctyPlus moctyPlus2 = moctyMapper.getMoctyPlus(mocty.getUdf05());
                if(moctyPlus2 == null) {
                    throw new CustomException("500", "该排产单数据不正确");
                }
                IHead iHead2 = iHeadService.getOne(new LambdaQueryWrapper<IHead>().eq(IHead::getMoctyudf05, mocty.getUdf05())
                        .eq(IHead::getJinzhanUuid, resource.getJinzhanUuid()).eq(IHead::getType, "SJ"));
                if(iHead2 != null) moctyPlus2.setSjNo(iHead2.getUid().toString());
                moctyPlus2.setBgNums(sfcteMapper.getAlreadyBGmocty(mocty.getUdf05(), mocty.getTy019()));
                moctyPlusList.add(moctyPlus2);
                // 计算今日排产量
                moctyPlus2.setTy001(moctyPlus2.getTy001().trim());
                moctyPlus2.setTy002(moctyPlus2.getTy002().trim());
                List<MoctyPlus> tList = new ArrayList<>();  tList.add(moctyPlus2);
                List<SelMoctyScheduleTypeVo> list = moctyMapper.selMoctyScheduleType(TimeUtils.HZStdTime(), tList);
                if(list != null && list.size() > 0) {
                    Double x = new Double(0);
                    for(SelMoctyScheduleTypeVo t : list) {
                        x += t.getTY004();
                    }
                    moctyPlus2.setNowDateNums(x);
                }
            }
            if(moctyPlusList.size() == 1) {
                moctyPlus.setNowDateNums(moctyPlusList.get(0).getNowDateNums());
            }
            moctyPlus.setAllGongDans(moctyPlusList);
        }
        return Result.success(moctyPlus);
    }

    @ApiOperation("通过机器编号,获取mocty")
    @PostMapping("moctyListByResourceId")
    public Result<List<MoctyPlus>> moctyListByResourceId(@RequestBody MoctyListByResourceIdDto dto) {
        Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMachineNo()));
        List<String> statusList = new ArrayList<>();
        statusList.add(MOCStatusEnum.DaiShouJian.getValue());  statusList.add(MOCStatusEnum.ShouJianZhong.getValue());
        statusList.add(MOCStatusEnum.DaiJinZhan.getValue());  statusList.add(MOCStatusEnum.ShengChanZhong.getValue());
        statusList.add(MOCStatusEnum.ZanTing.getValue()); statusList.add(MOCStatusEnum.DaiMuJuQueRen.getValue());
        statusList.add(MOCStatusEnum.DaiShangLiaoQueRen.getValue()); statusList.add(MOCStatusEnum.DaiKaiJi.getValue());
        List<MoctyPlus> moctyList = moctyMapper.moctyListByResourceIdMocta(dto.getDate(), resource.getResourceGroupIdIsF().toString(), statusList);

        for(MoctyPlus moctyPlus : moctyList) {
            if("ST4".equals(moctyPlus.getWorkCenterId().trim()) || "ST6".equals(moctyPlus.getWorkCenterId().trim())) {
                moctyPlus.setSfctaVoList(sfcteMapper.querySfctaVo(moctyPlus.getTy001(), moctyPlus.getTy002()));
            }
        }

//        List<MoctyPlus> moctyList = moctyMapper.moctyListByResourceId(dto.getDate(), resource.getResourceGroupIdIsF().toString(), statusList);
//        List<Mocty> moctyList = moctyMapper.selectList(new LambdaQueryWrapper<Mocty>().eq(Mocty::getTy003, date).eq(Mocty::getTy009, one.getResourceGroupId()));
        return Result.success(moctyList);
    }

    @Log("上料确认")
    @ApiOperation("上料确认")
    @DSTransactional
    @PostMapping("shangLiaoComfirm")
    public Result shangLiaoComfirm(@RequestBody ComfirmResourceDto dto) {
        Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
        if(!MOCStatusEnum.DaiShangLiaoQueRen.getValue().equals(mocty.getUdf01().trim())) {
            return Result.error("当前工单状态不是待上料确认中");
        }
        List<Mocty> moctyList = getTongZuMocty(mocty);
        for(Mocty mocty1 : moctyList) {
            // 将模具放进  表中
            Mocty t = new Mocty();  t.setUdf01(MOCStatusEnum.DaiKaiJi.getValue());
            moctyMapper.update(t, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, mocty1.getUdf05()));
        }
        return Result.success();
    }

    private List<Mocty> getTongZuMocty(Mocty mocty) {
        List<Mocty> moctyList = new ArrayList<>();
        if(StringUtils.isNotEmpty(mocty.getUdf02())) {
            moctyList = moctyMapper.selectList(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf02, mocty.getUdf02()));
        }else{
            moctyList.add(mocty);
        }
        return moctyList;
    }

    @Log("模具确认")
    @ApiOperation("模具确认")
    @DSTransactional
    @PostMapping("comfirmResource")
    public Result comfirmResource(@RequestBody ComfirmResourceDto dto) {
        Mocty mocty1 = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
        if(!MOCStatusEnum.DaiMuJuQueRen.getValue().equals(mocty1.getUdf01().trim())) {
            return Result.error("当前工单状态不是[待确认模具]中");
        }

        List<Mocty> moctyList = getTongZuMocty(mocty1);
        for(Mocty mocty : moctyList) {
            Mocty t = new Mocty();  t.setUdf01(MOCStatusEnum.DaiShangLiaoQueRen.getValue());
            moctyMapper.update(t, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, mocty.getUdf05()));
        }

        Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getMoctyudf05, dto.getUuid()));
        if(resource == null) {
            throw new CustomException("500", "当前工单没有进站");
        }

        // 查看当前机器中的模具，和工装。是否和一样。
        List<Workresource> workresourceList = workresourceMapper.selectList(new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, dto.getUuid()));
        Set<Integer> set = new HashSet<>();
        for(Workresource x : workresourceList) {
            if(x.getResourceId() != null && x.getResourceGroupId() != null && !x.getResourceTypeId().equals(1) && !x.getResourceTypeId().equals(2)) {
                set.add(x.getResourceId());
            }
        }
        List<Maconlineinfo> list = maconlineinfoMapper.selectList(new LambdaQueryWrapper<Maconlineinfo>().eq(Maconlineinfo::getMacid, moctyList.get(0).getUdf08()));
        Set<Integer> onlineSet = new HashSet<>();
        for(Maconlineinfo x : list) {
           onlineSet.add(x.getResourceId());
        }

        if(onlineSet.size() > 0 && set.size() > 0 && !onlineSet.equals(set)) {
            throw new CustomException("500", "机台指派内容和当前机台模具信息不一致.");
        }

        // 插入首检单
        List<IHead> iHeadList = new ArrayList<>();
        List<IBody> iBodyList = new ArrayList<>();
        Long uid = qmsmgMapper.uid();
        long idx = 0;
        if(set.size() > 0 && !onlineSet.equals(set)) {
//            set.removeAll(onlineSet);
//            StringBuffer sb = new StringBuffer();
//            for(String s : set) {
//                for(Workresource x : workresourceList) {
//                    if(x.getResourceNO().trim().equals(s.trim())) {
//                        sb.append(x.getResourceNO().trim()).append(" , ");
//                        break;
//                    }
//                }
//            }
//            if(sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
            throw new CustomException("500", "机台指派内容和当前机台已有信息不一致.");
        }
        for(Mocty mocty : moctyList) {
            // 生成首检单
            AddFirstInspectionXianChangNoInsertVo vo = qmsmgService.addFirstInspectionXianChangNoInsert(mocty.getUdf05().trim(), resource.getJinzhanUuid(), uid + idx);
            idx++;
            if(vo.getCode() == null || vo.getCode() == 0) {
                MoctyPlus moctyPlus = moctyMapper.getMoctyPlus(mocty.getUdf05());
                throw new CustomException("500", "品号: " + moctyPlus.getProductId().trim() + "没有现场的首检项目");
            }
            iHeadList.addAll(vo.getIHeadList());
            iBodyList.addAll(vo.getIBodyList());
        }

        if(iHeadList.size() > 0) {
            iHeadService.saveBatch(iHeadList);
            for(IHead iHead : iHeadList) {
                // 消息通知
                znxService.saveZnxAndSendMessage(MessageTypeEnum.JIANYAN.getValue(),
                        "有一张首检单待处理, 单号：" + iHead.getUid(), ZnxStatusEnum.DAIBAN.getValue(), iHead.getType()+":"+iHead.getUid());
            }
        }
        if(iBodyList.size() > 0) iBodyService.saveBatch(iBodyList);

        return Result.success();
    }

//    @Log("模具确认测试")
//    @ApiOperation("模具确认测试")
//    @DSTransactional
//    @PostMapping("comfirmResourceTest")
    public Result comfirmResourceTest(@RequestBody ComfirmResourceDto dto) {
        Mocty mocty1 = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
        List<Mocty> moctyList = getTongZuMocty(mocty1);
        for(Mocty mocty : moctyList) {
            Mocty t = new Mocty();  t.setUdf01(MOCStatusEnum.DaiShangLiaoQueRen.getValue());
            moctyMapper.update(t, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, mocty.getUdf05()));
        }

        Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getMoctyudf05, dto.getUuid()));
        // 查看当前机器中的模具，和工装。是否和一样。
        List<Workresource> workresourceList = workresourceMapper.selectList(new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, dto.getUuid()));
        Set<Integer> set = new HashSet<>();
        for(Workresource x : workresourceList) {
            if(x.getResourceId() != null && x.getResourceGroupId() != null && !x.getResourceTypeId().equals(1) && !x.getResourceTypeId().equals(2)) {
                set.add(x.getResourceId());
            }
        }
        List<Maconlineinfo> list = maconlineinfoMapper.selectList(new LambdaQueryWrapper<Maconlineinfo>().eq(Maconlineinfo::getMacid, moctyList.get(0).getUdf08()));
        Set<Integer> onlineSet = new HashSet<>();
        for(Maconlineinfo x : list) {
            onlineSet.add(x.getResourceId());
        }
        List<IHead> iHeadList = new ArrayList<>();
        List<IBody> iBodyList = new ArrayList<>();
        Long uid = qmsmgMapper.uid();
        long idx = 0;
        for(Mocty mocty : moctyList) {
            // 生成首检单
            AddFirstInspectionXianChangNoInsertVo vo = qmsmgService.addFirstInspectionXianChangNoInsert(mocty.getUdf05().trim(), resource.getJinzhanUuid(), uid + idx);
            idx++;
            if(vo.getCode() == null || vo.getCode() == 0) {
                MoctyPlus moctyPlus = moctyMapper.getMoctyPlus(mocty.getUdf05());
                throw new CustomException("500", "品号: " + moctyPlus.getProductId().trim() + "没有现场的首检项目");
            }
            iHeadList.addAll(vo.getIHeadList());
            iBodyList.addAll(vo.getIBodyList());
        }


        if(iHeadList.size() > 0) iHeadService.saveBatch(iHeadList);
        if(iBodyList.size() > 0) iBodyService.saveBatch(iBodyList);
        return Result.success();
    }

    @Log("换机")
    @ApiOperation("换机")
    @DSTransactional
    @PostMapping("changeMachine")
    public Result changeMachine(@RequestBody ChangeMachineDto dto) {
        if(StringUtils.isEmpty(dto.getUuid()) || StringUtils.isEmpty(dto.getResourceNo()) || StringUtils.isEmpty(dto.getResourceName())
        || StringUtils.isEmpty(dto.getDate()) || dto.getResourceId() == null) {
            throw new CustomException("500", "参数都不能为空!!!!");
        }
        // 将原UUID的排产数据，改成已报工数量
        // 然后将剩余数量，转到新日期，新机器上
        BigDecimal bgNums = sfcteMapper.getAlreadyBGmocty(dto.getUuid(), "0010");
        if(bgNums == null) bgNums = new BigDecimal(0D);

        Mocty oldMocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
        if(oldMocty == null) {
            throw new CustomException("500", "排产单号: " + dto.getUuid() + ":不存在");
        }
        if(!MOCStatusEnum.ShengChanZhong.getValue().equals(oldMocty.getUdf01().trim())) {
            throw new CustomException("500", "排产单不在" + MOCStatusEnum.ShengChanZhong.getValue());
        }
        Mocty t = new Mocty();  t.setTy004(bgNums.doubleValue());
        t.setUdf03("换机操作，保留报工数量" + bgNums.doubleValue() + "。其余的转入新排产。" + oldMocty.getUdf03());
        moctyMapper.update(t, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));

        Mocty mocty = new Mocty();
        mocty.setCompany("");
        mocty.setCreateDate(TimeUtils.getNowTime());
        mocty.setCreator(SecurityUtils.getLoginUser().getUsername());
        mocty.setFlag(1D);
        mocty.setTy001(oldMocty.getTy001());
        mocty.setTy002(oldMocty.getTy002());
        mocty.setTy003(dto.getDate());
        mocty.setTy004(new BigDecimal(oldMocty.getTy004()).subtract(bgNums).doubleValue());
        mocty.setTy009(dto.getResourceId().toString());
        mocty.setTy019(oldMocty.getTy019());
        mocty.setUdf01(MOCStatusEnum.DaiJinZhan.getValue());
        mocty.setUdf03("从排产单号: " + dto.getUuid().trim() + "中换机转入.");
        mocty.setUdf05(UUID.randomUUID().toString());

        // copy一份到workresource到新的Mocty (但是不copy 生产线/机器)
        // 过滤掉 机器/生产线的workresource， 其余copy,然后新增一个

        List<Resourcegroup> list = resourcegroupMapper.selectList(null);
        Map<Integer, Resourcegroup> posMap = new HashMap<>();
        for(Resourcegroup resourcegroup : list) {
            posMap.put(resourcegroup.getResourceGroupId(), resourcegroup);
        }
        Integer originMacId = null;  String originMacNo = null;  String originMacName = null;
        List<Workresource> workresourceList = workresourceMapper.selectList(new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, dto.getUuid()));
        for(Workresource workresource : workresourceList) {
            if(workresource.getResourceGroupId() == null || workresource.getResourceGroupId().equals(0)) continue;
            Integer originId = resourcegroupService.getOriginIdById(workresource.getResourceGroupId(), posMap);
            if(originId.equals(1) || originId.equals(2)) {
                originMacId = workresource.getResourceId();
                Resourcegroup resourcegroup = posMap.get(originMacId);
                originMacNo = resourcegroup.getResourceGroupNO();
                originMacName = resourcegroup.getResourceGroupName();
                continue;
            }
            Workresource p = new Workresource();
            p.setWorkResourceId(UUID.randomUUID().toString());
            p.setWorkSingle(workresource.getWorkSingle());
            p.setWorkNo(workresource.getWorkNo());
            p.setProcessNo(workresource.getProcessNo());
            p.setProcessId(workresource.getProcessId());
            p.setResourceGroupId(workresource.getResourceGroupId());
            p.setResourceId(workresource.getResourceId());
            p.setDate(dto.getDate());
            p.setBeat(workresource.getBeat());
            p.setQuota(workresource.getQuota());
            p.setCreator(SecurityUtils.getLoginUser().getUsername());
            p.setCreateTime(TimeUtils.getFullNowTime());
            p.setProductLineId(mocty.getUdf05());
            workresourceService.save(p);
        }
        // 插入新的 机器/生产线
        Workresource p = new Workresource();
        p.setWorkResourceId(UUID.randomUUID().toString());
        p.setWorkSingle(oldMocty.getTy001());
        p.setWorkNo(oldMocty.getTy002());
        p.setProcessNo(oldMocty.getTy019());
        SFCTA sfcta = sfctaMapper.selectOne(new LambdaQueryWrapper<SFCTA>()
                .eq(SFCTA::getTA001, oldMocty.getTy001()).eq(SFCTA::getTA002, oldMocty.getTy002()).eq(SFCTA::getTA003, oldMocty.getTy019()));
        p.setProcessId(sfcta.getTA004());
        p.setResourceGroupId(posMap.get(dto.getResourceId()).getResourceGroupParentId());
        p.setResourceId(dto.getResourceId());
        p.setDate(dto.getDate());

        p.setBeat(0D);
        p.setQuota(0D);
        // TODO 看看有没有预设值，没有的话就全部填0.

        MOCTA mocta = moctaMapper.selectOne(new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA001, mocty.getTy001())
                .eq(MOCTA::getTA002, mocty.getTy002()));
        productprocessresourceMapper.selectOne(
                new LambdaQueryWrapper<Productprocessresource>()
                        .eq(Productprocessresource::getInv_no, mocta.getUDF04())
                        .eq(Productprocessresource::getProductId, mocta.getTA006())
                        .eq(Productprocessresource::getProcessRoute, mocta.getUDF02())
                        .eq(Productprocessresource::getInvrt_name, mocta.getUDF01())
                        .eq(Productprocessresource::getProcessId, mocta.getUDF03())
                        .eq(Productprocessresource::getProcessNo, mocty.getTy019())
                        .eq(Productprocessresource::getResourceTypeId, resourcegroupService.getOriginIdById(dto.getResourceId(), posMap))
                        .eq(Productprocessresource::getResourceGroupId, posMap.get(dto.getResourceId()).getResourceGroupParentId())
                        .eq(Productprocessresource::getMachiningCenter, mocta.getTA021()));

        p.setCreator(SecurityUtils.getLoginUser().getUsername());
        p.setCreateTime(TimeUtils.getFullNowTime());
        p.setProductLineId(mocty.getUdf05());
        workresourceService.save(p);

        Mochuanjilog mochuanjilog = new Mochuanjilog(mocty.getTy001(), mocty.getTy002(), mocty.getTy019(),
                oldMocty.getUdf05(), mocty.getUdf05(), mocty.getTy004(), originMacId, originMacNo, originMacName,
                dto.getResourceId(), dto.getResourceNo(), dto.getResourceName(), TimeUtils.getFullNowTime(), SecurityUtils.getLoginUser().getUsername());
        mochuanjilogService.save(mochuanjilog);

        return Result.success();
    }

    @Log("点击进站")
    @ApiOperation("点击进站")
    @DSTransactional
    @PostMapping("macOn")
    public Result macOn(@RequestBody MacOnDto dto) {

        Resource one = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMachineNo()));
        if(one == null) {
            throw new CustomException("500", "机器编号" + dto.getMachineNo() + ":不存在");
        }
        if(!MachineStatusEnum.XianZhi.getValue().equals(one.getStatus())) {
            throw new CustomException("500", "机台目前不是" + MachineStatusEnum.XianZhi.getValue() + "状态");
        }
        Integer resourceGroupId = one.getResourceGroupIdIsF();

        Mocty mocty2 = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
        if(mocty2 == null) {
            throw new CustomException("500", "工单" + dto.getUuid() + ":不存在");
        }
        List<Mocty> moctyList = getTongZuMocty(mocty2);
        if(!MOCStatusEnum.DaiJinZhan.getValue().equals(mocty2.getUdf01())) {
            throw new CustomException("500", "工单目前不是" + MOCStatusEnum.DaiJinZhan.getValue() + "状态");
        }

        // TODO 不是装配车间要查看, 模具和工装都选上。

        for(Mocty mocty : moctyList) {
            mocty.setUdf07(TimeUtils.getFullNowTime());
            mocty.setUdf08(resourceGroupId.toString());
            mocty.setUdf01(MOCStatusEnum.DaiMuJuQueRen.getValue());
            moctyMapper.update(mocty, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, mocty.getUdf05()));
        }

        List<Macstatuslog> macstatuslogList = new ArrayList<>();
        List<Moclog> moclogList = new ArrayList<>();
        for(Mocty mocty : moctyList) {
            Macstatuslog log = new Macstatuslog();
            log.setCreator(SecurityUtils.getLoginUser().getUsername());
            log.setCreatetime(TimeUtils.getNowTime());
            log.setMacid(one.getResourceGroupIdIsF());  log.setMacno(one.getDeviceid());  log.setMacname(one.getDevicename());
            log.setMoctyudf05(mocty.getUdf05());
//            log.setOrder(qmsmgMapper.macOnOrderByUUid(dto.getUuid()));
            log.setMacStatus(MachineStatusEnum.JiaGong.getValue());
            log.setTa001(mocty.getTy001());  log.setTa002(mocty.getTy002());
            macstatuslogList.add(log);

            Moclog moclog = new Moclog();
            moclog.setTa001(mocty.getTy001());
            moclog.setTa002(mocty.getTy002());
            moclog.setMoctyudf05(mocty.getUdf05());
            moclog.setStatus(MOCStatusEnum.ShengChanZhong.getValue());
            moclog.setCreator(SecurityUtils.getLoginUser().getUsername());
            moclog.setCreatetime(TimeUtils.getFullNowTime());
            moclog.setMacid(one.getResourceGroupIdIsF());
            moclog.setMacno(one.getDeviceid());
            moclog.setMacname(one.getDevicename());
            moclog.setRemark("工单已进站");
            moclogList.add(moclog);
        }
        macstatuslogService.saveBatch(macstatuslogList);
        moclogService.saveBatch(moclogList);

//        DynamicDataSourceContextHolder.push("mes");
        one.setStatus(MachineStatusEnum.JiaGong.getValue());
        one.setMoctyudf05(dto.getUuid());  // 隨便幫一個MOCTY
        one.setJinzhanTime(TimeUtils.getFullNowTime());
        one.setJinzhanUuid(UUID.randomUUID().toString());
//        one.setInspectionTime(one.getChangeTime());
//        one.setChangeTime(TimeUtils.getNowTime());

//        Integer order = qmsmgMapper.orderByUUid(dto.getUuid());
//        one.setOrderNum(order);
        Jinchuzhanlog jinchuzhanlog = new Jinchuzhanlog();
        jinchuzhanlog.setJinchuzhanuuid(one.getJinzhanUuid());
        jinchuzhanlog.setJinzhantime(one.getJinzhanTime());
        jinchuzhanlogMapper.insert(jinchuzhanlog);

        resourceService.update(one, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMachineNo()));

        // 如果是裝配，沒有點檢單
        // 生成点检单
//        if(one.getResourceType().equals(1)) {
//            Eqtte eqtte = new Eqtte();
//            eqtte.setTE001("DJD");
//            eqtte.setTE002(eqtteMapper.selTe002(eqtte.getTE001()));
//            eqtte.setTE003(TimeUtils.HZStdTime());
//            eqtte.setTE004("2");
//            eqtte.setTE008("1");
//            eqtte.setTE010(one.getResourceGroupIdIsF().toString());
//            eqtte.setTE011(one.getDeviceid());
//            eqtte.setTE012(one.getDevicename());
//            eqtte.setTE019("0");
//            eqtte.setTE027("进站自动生成");
//            eqtte.setTE031(TimeUtils.HZStdTime());
//            eqtte.setTE032(TimeUtils.HZStdTime());
//            eqtte.setTE059(one.getResourceGroupIdIsF().toString());  // 现在模具在哪个机器ID
//            eqtte.setTE060(one.getDeviceid());
//            eqtte.setTE061(one.getDevicename());
//            eqtte.setTE062(one.getJinzhanUuid());  // 绑定进站的UUID,看是哪个进站的UUID的点检单
//            eqtte.setCREATE_DATE(TimeUtils.getFullNowTime());
//            eqtte.setCREATOR("ERP");
//            eqtteMapper.insert(eqtte);
//
//            // 获取单身的项目 通过planitem
            List<Maintainplanitem> itemList = maintainplanMapper.jiQiDianJianItemList();
//            int idx = 1;
//            for(Maintainplanitem item : itemList) {
//                Eqttf eqttf = new Eqttf();
//                eqttf.setTF001(eqtte.getTE001());
//                eqttf.setTF002(eqtte.getTE002());
//                eqttf.setTF003(""+idx);  idx++;
//                eqttf.setUDF01(item.getMpiid());  // 维护编号
//                eqttf.setUDF02(item.getMpiname());  // 维护名称
//                eqttf.setTF005(item.getMpicontent());  // 维护内容
//                eqttf.setTF008(item.getMpiresulttype());  // 结果类型 1.文字 2.数值 3.日期[DEF:1]
//                eqttf.setCREATE_DATE(TimeUtils.getNowTime());
//                eqttf.setCREATOR("ERP");
//                eqttfMapper.insert(eqttf);
//            }
//
//            // 消息通知
//            znxService.saveZnxAndSendMessage(MessageTypeEnum.DIANJIAN.getValue(),
//                    "有一张点检单待处理, 单号：" + eqtte.getTE002(), ZnxStatusEnum.DAIBAN.getValue(), eqtte.getTE001()+":"+eqtte.getTE002());
//
//        }

        return Result.success("进站成功");
    }

    @Log("点击出站(完工)")
    @ApiOperation("点击出站(完工)")
    @DSTransactional
    @PostMapping("macOff")
    public Result macOff(@RequestBody MacOffDto dto) {
        Resource one = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMachineNo()));
        if(one == null) {
            throw new CustomException("500", "机器编号" + dto.getMachineNo() + ":不存在");
        }
        Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
        if(mocty == null) {
            throw new CustomException("500", "排产单" + dto.getUuid() + ":不存在");
        }
//        if(!MOCStatusEnum.ShengChanZhong.getValue().equals(mocty.getUdf01())) {
//            throw new CustomException("500", "该工单目前没有上机");
//        }
        if(!one.getResourceGroupIdIsF().toString().trim().equals(mocty.getUdf08().trim())) {
            throw new CustomException("500", "该排产并不在此机台: " + dto.getMachineNo());
        }

        Jinchuzhanlog jinchuzhanlog = jinchuzhanlogMapper.selectOne(new LambdaQueryWrapper<Jinchuzhanlog>().eq(Jinchuzhanlog::getJinchuzhanuuid, dto.getJinchuzhanuuid()));
        if(jinchuzhanlog == null) {
            throw new CustomException("500", "进出站UUID不对");
        }
        jinchuzhanlog.setOutzhantime(TimeUtils.getFullNowTime());
        jinchuzhanlogMapper.update(jinchuzhanlog, new LambdaQueryWrapper<Jinchuzhanlog>().eq(Jinchuzhanlog::getJinchuzhanuuid, dto.getJinchuzhanuuid()));

        List<Mocty> moctyList = getTongZuMocty(mocty);
        for(Mocty mocty1 : moctyList) {
            // 两个记录表
            Macstatuslog log = new Macstatuslog();
            log.setCreator(SecurityUtils.getLoginUser().getUsername());
            log.setCreatetime(TimeUtils.getNowTime());
            log.setMacid(one.getResourceGroupIdIsF());  log.setMacno(one.getDeviceid());  log.setMacname(one.getDevicename());
            log.setMoctyudf05(mocty1.getUdf05());
            log.setMacStatus(MachineStatusEnum.XianZhi.getValue());
            log.setTa001(mocty1.getTy001());  log.setTa002(mocty1.getTy002());
            macstatuslogService.save(log);

            Moclog moclog = new Moclog();
            moclog.setTa001(mocty1.getTy001());
            moclog.setTa002(mocty1.getTy002());
            moclog.setMoctyudf05(mocty1.getUdf05());
            moclog.setStatus(MOCStatusEnum.ChuZhan.getValue());
            moclog.setCreator(SecurityUtils.getLoginUser().getUsername());
            moclog.setCreatetime(TimeUtils.getFullNowTime());
            moclog.setMacid(one.getResourceGroupIdIsF());
            moclog.setMacno(one.getDeviceid());
            moclog.setMacname(one.getDevicename());
            moclog.setRemark("工单已出站");
            moclogService.save(moclog);

            BigDecimal bgNums = sfcteMapper.getAlreadyBGmocty(mocty1.getUdf05(), mocty1.getTy019());
            if(bgNums.compareTo(new BigDecimal(mocty1.getTy004())) >= 0) {
                mocty1.setUdf01(MOCStatusEnum.YiWanGong.getValue());
            }else{
                mocty1.setUdf01(MOCStatusEnum.DaiJinZhan.getValue());
            }
            mocty1.setUdf07("");  // 进站时间
            mocty1.setUdf08("");  // 机器ID
            moctyMapper.update(mocty1, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, mocty1.getUdf05()));
        }

        inspectiontimeMapper.delete(new LambdaQueryWrapper<Inspectiontime>().eq(Inspectiontime::getJinzhanuuid, dto.getJinchuzhanuuid()));

        Resource resource = new Resource();
        resource.setStatus(MachineStatusEnum.XianZhi.getValue());
        resource.setMoctyudf05("");
        resource.setChangeTime("");
        resource.setInspectionTime("");
        resource.setJinzhanUuid("");
        resource.setJinzhanTime("");
        // 修改机器的状态
        resourceService.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMachineNo()));

        // 将所有该机器上的模具/工装，全部都退下.
        // 该台机器上所有的工装/模具
        List<Maconlineinfo> maconlineinfoList = maconlineinfoMapper.selectList(new LambdaQueryWrapper<Maconlineinfo>()
                .eq(Maconlineinfo::getMacno, one.getDeviceid()));
        if(maconlineinfoList != null && maconlineinfoList.size() > 0) {
            for(Maconlineinfo maconlineinfo: maconlineinfoList) {
                maconlineinfo.setMouldOutTime(TimeUtils.getFullNowTime());
                // 将这条转移到历史表中。 然后删掉
                Maconlineinfohistory history = new Maconlineinfohistory();
                BeanUtils.copyPropertiesIgnoreCase(maconlineinfo, history);
                maconlineinfohistoryMapper.insert(history);
                maconlineinfoMapper.delete(new LambdaQueryWrapper<Maconlineinfo>()
                        .eq(Maconlineinfo::getMacno, maconlineinfo.getMacno())
                        .eq(Maconlineinfo::getResourceno, maconlineinfo.getResourceno())
                        .eq(Maconlineinfo::getResourcetype, maconlineinfo.getResourcetype()));
                resource.setStatus(MouldStatusEnum.DaiGuiHuan.getValue());
                resource.setMacOnTime("");  // 改一下上模时间
                resource.setMaintainTime("");
                resourceMapper.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, maconlineinfo.getResourceno()));




            }
        }
        return Result.success("出站成功");
    }

    @Log("批量生产")
    @ApiOperation("批量生产")
    @DSTransactional
    @PostMapping("batchProduction/{uuid}")
    public Result batchProduction(@PathVariable String uuid) {

        Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getStatus, MachineStatusEnum.JiaGong.getValue())
                .eq(Resource::getMoctyudf05, uuid));
        if(resource == null) {
            throw new CustomException("500", uuid + "并不在" + MachineStatusEnum.JiaGong.getValue() + "中");
        }
//        IHead iHead = iHeadService.getOne(new LambdaQueryWrapper<IHead>().eq(IHead::getType, "SJ").eq(IHead::getMoctyudf05, uuid)
//                .eq(IHead::getOrderNum, resource.getOrderNum()));
//        if(iHead != null) {
//            throw new CustomException("500", "已存在首检单");
//        }

        Mocty mocty1 = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, uuid));
        if(!MOCStatusEnum.DaiKaiJi.getValue().equals(mocty1.getUdf01().trim())) {
            throw new CustomException("500", "工单状态并不在待开机中");
        }
        List<Mocty> moctyList = getTongZuMocty(mocty1);
        for(Mocty mocty : moctyList) {
            mocty.setUdf01(MOCStatusEnum.ShengChanZhong.getValue());
            moctyMapper.update(mocty, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, mocty.getUdf05()));
            // 记录表
            Moclog moclog = new Moclog();
            moclog.setTa001(mocty.getTy001());
            moclog.setTa002(mocty.getTy002());
            moclog.setMoctyudf05(mocty.getUdf05());
            moclog.setCreator(SecurityUtils.getLoginUser().getUsername());
            moclog.setCreatetime(TimeUtils.getFullNowTime());
            moclog.setMacid(resource.getResourceGroupIdIsF());
            moclog.setMacno(resource.getDeviceid());
            moclog.setMacname(resource.getDevicename());
            moclog.setRemark("批量生产");
            moclog.setOrderNum(resource.getOrderNum());
            moclogService.save(moclog);
        }

        return Result.success();
    }

    @Log("人员签到(上机)")
    @ApiOperation("人员签到(上机)")
    @DSTransactional
    @PostMapping("personQianDao")
    public Result personQianDao(@RequestBody PersonQianDaoDto dto) {
        if(StringUtils.isEmpty(dto.getPersonNO()) || StringUtils.isEmpty(dto.getPersonName())) {
            throw new CustomException("500", "人员编号和名称不能为空");
        }
        if(StringUtils.isEmpty(dto.getMacNo())) {
            throw new CustomException("500", "机台编号不能为空");
        }
        Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMacNo()));
        if(resource == null) {
            throw new CustomException("500", "机台编号不存在");
        }
        if(StringUtils.isNotEmpty(resource.getWorkPersonId()) || StringUtils.isNotEmpty(resource.getQiandaouuid())) {
            throw new CustomException("500", "当前机台已有人上机." + resource.getWorkPersonName());
        }
        Resource t = new Resource();
        t.setQiandaouuid(UUID.randomUUID().toString());
        t.setWorkPersonId(dto.getPersonNO());
        t.setWorkPersonName(dto.getPersonName());
        t.setWorkPersonTime(TimeUtils.getFullNowTime());
        resourceService.update(t, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMacNo()));

        Mocworklog mocworklog = new Mocworklog
                (dto.getPersonNO(), dto.getPersonName(), dto.getMacNo(), "上机", TimeUtils.getFullNowTime(), SecurityUtils.getLoginUser().getUsername());
        mocworklogService.save(mocworklog);

        Personinout personinout = new Personinout();
        personinout.setQiandaouuid(t.getQiandaouuid());
        personinout.setMacid(resource.getResourceGroupIdIsF());
        personinout.setMacno(resource.getDeviceid());
        personinout.setMacname(resource.getDevicename());
        personinout.setPersonno(dto.getPersonNO());
        personinout.setPersonname(dto.getPersonName());
        personinout.setIntime(t.getWorkPersonTime());
        personinoutMapper.insert(personinout);

        return Result.success("上机完成");
    }

    @Log("人员签退(下机)")
    @ApiOperation("人员签退(下机)")
    @DSTransactional
    @PostMapping("personQianTui")
    public Result personQianDao(@RequestBody PersonQianTuiDto dto) {
        if(StringUtils.isEmpty(dto.getPersonNO()) || StringUtils.isEmpty(dto.getPersonName())) {
            throw new CustomException("500", "人员编号和名称不能为空");
        }
        if(StringUtils.isEmpty(dto.getMacNo())) {
            throw new CustomException("500", "机台编号不能为空");
        }
        Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMacNo()));
        if(resource == null) {
            throw new CustomException("500", "机台编号不存在");
        }
        if(StringUtils.isEmpty(resource.getWorkPersonId()) || StringUtils.isEmpty(resource.getQiandaouuid())) {
            throw new CustomException("500", "当前机台没人上机");
        }
        if(!resource.getQiandaouuid().trim().equals(dto.getQiandaoUuid())) {
            throw new CustomException("500", "签到UUID,对不上");
        }

        Resource t = new Resource();
        t.setWorkPersonId("");
        t.setWorkPersonName("");
        t.setWorkPersonTime("");
        t.setQiandaouuid("");
        resourceService.update(t, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMacNo()));

        Mocworklog mocworklog = new Mocworklog
                (dto.getPersonNO(), dto.getPersonName(), dto.getMacNo(), "下机", TimeUtils.getFullNowTime(), SecurityUtils.getLoginUser().getUsername());
        mocworklogService.save(mocworklog);

        Personinout personinout = new Personinout();
        personinout.setOuttime(TimeUtils.getFullNowTime());
        personinoutMapper.update(personinout, new LambdaQueryWrapper<Personinout>().eq(Personinout::getQiandaouuid, dto.getQiandaoUuid()));

        return Result.success("下机完成");
    }

    @Log("人员签到签退列表")
    @ApiOperation("人员签到签退列表 上下机历史记录")
    @PostMapping("sxjHistoryList")
    public Result<PageInfo<List<Mocworklog>>> sxjHistoryList(@RequestBody SxjHistoryListDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<Mocworklog> list = mocworklogMapper.sxjHistoryList(dto);
        PageInfo<List<Mocworklog>> pageInfo = new PageInfo(list);
        return Result.success(pageInfo);
    }

    @Log("查询MOCTY中没有排产到具体设备的")
    @ApiOperation("查询MOCTY中没有排产到具体设备的")
    @PostMapping("noDeviceMoctyList")
    public Result<PageInfo<List<MoctyPlus>>> noDeviceMoctyList(@RequestBody NoDeviceMoctyListDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<MoctyPlus> list = moctyMapper.noDeviceMoctyList(dto);
        PageInfo<List<MoctyPlus>> pageInfo = new PageInfo(list);
        return Result.success(pageInfo);
    }

    @Log("MOCTY添加具体设备/生产线")
    @ApiOperation("MOCTY添加具体设备/生产线")
    @PostMapping("addDevice")
    @DSTransactional
    public Result addDevice(@RequestBody List<AddMoctyDeviceDto> list) {
        for(AddMoctyDeviceDto dto : list) {
            if(StringUtils.isEmpty(dto.getResourceGroupId()) || StringUtils.isEmpty(dto.getUuid())) {
                throw new CustomException("500", "机台编号或排产ID为空");
            }
            if(!MoneyUtils.isNumber(dto.getResourceGroupId())) {
                throw new CustomException("500", "资源组编号格式不正确");
            }
            Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));
            if(mocty == null) {
                throw new CustomException("500", "排产数据不存在");
            }
            Mocty t = new Mocty();  t.setTy009(dto.getResourceGroupId());
            t.setUdf01(MOCStatusEnum.DaiJinZhan.getValue());
            moctyMapper.update(t, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getUuid()));

            SFCTA sfcta = sfctaMapper.selectOne(new LambdaQueryWrapper<SFCTA>().eq(SFCTA::getTA001, mocty.getTy001()).eq(SFCTA::getTA002, mocty.getTy002()));
            Resourcegroup resourcegroup = resourcegroupService.getOne(new LambdaQueryWrapper<Resourcegroup>()
                    .eq(Resourcegroup::getResourceGroupId, Integer.parseInt(dto.getResourceGroupId())));

            Workresource workresource = new Workresource();
            workresource.setWorkResourceId(UUID.randomUUID().toString());
            workresource.setWorkSingle(mocty.getTy001());
            workresource.setWorkNo(mocty.getTy002());
            workresource.setProcessNo(mocty.getTy019().trim());  // 工序号
            workresource.setProcessId(sfcta == null ? "****" : sfcta.getTA004());   // 工艺号
            workresource.setResourceGroupId(resourcegroup.getResourceGroupParentId());  // 资源组ID
            workresource.setResourceId(Integer.parseInt(dto.getResourceGroupId().trim()));    // 具体所选的资源ID
            workresource.setDate(mocty.getTy003());
            workresource.setCreator(SecurityUtils.getLoginUser().getUsername());
            workresource.setCreateTime(TimeUtils.getFullNowTime());
            workresource.setProductLineId(mocty.getUdf05());   // 和生产线进行绑定
            workresourceService.save(workresource);

        }
        return Result.success();
    }

    @ApiOperation("设备里的工单状态")
    @PostMapping("shengChanStatus")
    public Result<ShengChanStatusVo> shengChanStatus(@RequestBody ShengChanStatusDto dto) {
        Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMacNo()));
        ShengChanStatusVo vo = new ShengChanStatusVo();
        BeanUtils.copyPropertiesIgnoreCase(resource, vo);
        return Result.success(vo);
    }

    @Log("添加[生产线/机器] 机台指派")
    @DSTransactional
    @ApiOperation("添加[生产线/机器]  机台指派")
    @PostMapping("jiTaiZhiPai")
    public Result jiTaiZhiPai(@RequestBody List<JiTaiZhiPaiDto> dto) {
//        List<Resourcegroup> list = resourcegroupMapper.selectList(null);
//        Map<Integer, Resourcegroup> posMap = new HashMap<>();
//        for(Resourcegroup t : list) {
//            posMap.put(t.getResourceGroupId(), t);
//        }

        List<Workresource> workresourceList = new ArrayList<>();
        for(JiTaiZhiPaiDto t : dto) {
            // 先删除workresource里面的东西。然后重新插入
            workresourceMapper.delete(new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, t.getProductLineId()));
            Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, t.getProductLineId()));

            if(!MOCStatusEnum.DaiJinZhan.getValue().equals(mocty.getUdf01().trim()) &&
            !MOCStatusEnum.DaiPaiJi.getValue().equals(mocty.getUdf01().trim())) {
                throw new CustomException("500", "工单状态不是待进站或待排机,不能修改");
            }
            mocty.setUdf02(t.getUuid());  // 同组的，写一样的UUID
            mocty.setTy009("****");
            mocty.setUdf01(MOCStatusEnum.DaiPaiJi.getValue());
            mocty.setUdf10(TimeUtils.getFullNowTime());   // 机台指派时间
            moctyMapper.update(mocty, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, t.getProductLineId()));
            for(JiTaiZhiPaiItemDto item : t.getItemList()) {
                Workresource workresource = new Workresource();
                workresource.setProductLineId(t.getProductLineId());
                workresource.setWorkResourceId(UUID.randomUUID().toString());
                workresource.setDate(TimeUtils.HZStdTime());
                BeanUtils.copyPropertiesIgnoreCase(item, workresource);
                workresource.setCreator(SecurityUtils.getLoginUser().getUsername());
                workresource.setCreateTime(TimeUtils.getFullNowTime());

//                Integer originIdById = resourcegroupService.getOriginIdById(workresource.getResourceGroupId(), posMap);
                workresource.setPeopleNum(item.getPeopleNum());
                workresource.setResourceTypeId(item.getResourceType());
                workresourceList.add(workresource);
                if(item.getResourceType().equals(1) || item.getResourceType().equals(2)) {
                    mocty.setTy009(item.getResourceId().toString());
                    mocty.setUdf01(MOCStatusEnum.DaiJinZhan.getValue());
                    moctyMapper.update(mocty, new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, t.getProductLineId()));
                }
            }
        }
        workresourceService.saveBatch(workresourceList);
        return Result.success("添加成功");
    }

    @ApiOperation("加工中的模具/工装")
    @PostMapping("macOnlineList")
    public Result<List<Maconlineinfo>> macOnlineList(@RequestBody MacOnlineListDto dto) {
        List<Maconlineinfo> maconlineinfoList = maconlineinfoMapper.selectList(new LambdaQueryWrapper<Maconlineinfo>().eq(Maconlineinfo::getResourceno, dto.getDeviceId()));
        return Result.success(maconlineinfoList);
    }

    @Log("一键恢复到原始状态")
    @ApiOperation("一键恢复到原始状态")
    @PostMapping("backback")
    @DSTransactional
    public Result backback() {
        // 所有加工中的工单全部变成不加工
        // 所有机器，模具，全部恢复成闲置
        resourceMapper.backMysqlData();
        resourceMapper.backSQLSERVERData();
//        moctyMapper.backTo();
//        resourceMapper.resetResourceStatus();
        // 删除 online表中正在用的信息。   删除onlineHis表
        // 删除领模，退模单
        // 清空人员上下机表
        // 清空报工单


        return Result.success();
    }


//    @Log("查询MOCTY中分配到具体任务的情况")
//    @ApiOperation("查询MOCTY中分配到具体任务的情况")
//    @PostMapping("moctyBindingResourceList")
//    public Result moctyBindingResourceList(@RequestBody NoDeviceMoctyListDto dto) {
//        List<MoctyBindingResourceVo> res = moctyMapper.moctyList(dto);
//        for(MoctyBindingResourceVo t : res) {
////            t.setMachinesList();
//        }
//        return Result.success(res);
//    }

//    @ApiOperation("按照销售订单展示排产")
//    @PostMapping("scheduleListByCoptc2")
//    public Result<PageInfo<PCorderList>> scheduleListByCoptc2(@RequestBody PCcoptcDto dto) {
//        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
//        List<Coptd> list = coptdMapper.coptdList(dto);
//        PageInfo<Coptd> pageInfo = new PageInfo(list);
//        List<PCorderList> res = new ArrayList<>();
//        // 审核码是Y  结束码是N
////        List<Coptd> list = coptdService.list(new LambdaQueryWrapper<Coptd>().eq(Coptd::getTd016, "N").eq(Coptd::getTd021, "Y"));
//
//        for(Coptd coptd : pageInfo.getList()) {
//            PCorderList zhi = new PCorderList();
//            zhi.setMoctaDiGui(scheduleService.COPTDStage(coptd.getTd001().trim(), coptd.getTd002().trim(), coptd.getTd003().trim(), coptd.getTd004().trim()));
//            zhi.setOrderType(coptd.getTd001());  zhi.setOrderNo(coptd.getTd002());  zhi.setOrderSerialNo(coptd.getTd003());
//            res.add(zhi);
//        }
//        PageInfo<PCorderList> ans = new PageInfo(list);
//        BeanUtils.copyPropertiesIgnoreCase(pageInfo, ans);
//        ans.setList(res);
//        return Result.success(ans);
//    }

//    @ApiOperation("按照销售订单展示排产")
//    @PostMapping("test/{a}/{b}/{c}/{d}")
//    public Result test(@PathVariable String a, @PathVariable String b, @PathVariable String c, @PathVariable String d) {
//        return scheduleService.COPTDStage(a,b,c,d);
////        return Result.success("删除成功");
//    }

}